package controller

import (
	"user-go/entity"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sgin"
	"github.com/androidsr/sc-go/sorm"
	"github.com/gin-gonic/gin"
)

func init() {
	sgin.AddRouter(SysUsersController{})
}

type SysUsersController struct {
}

// 查询
// @Router [get] [/sysusers/:id]
func (SysUsersController) Get(c *gin.Context) any {
	id := c.Param("id")
	data := new(entity.SysUsers)
	data.Account = id
	err := sorm.DB.GetOne(data)
	if err != nil {
		return model.NewFailDefault("获取对象失败")
	}
	data.Pass = ""
	return data
}

// 增加
// @Router [post] [/sysusers]
func (SysUsersController) Post(c *gin.Context, in *entity.SysUsers) any {
	if in.Account == "" {
		return model.NewFailDefault("账号不能为空")
	}
	sorm.DB.Insert(in)
	return model.NewOK(nil)
}

// 修改
// @Router [put] [/sysusers/edit]
func (SysUsersController) Put(c *gin.Context, in *entity.SysUsers) any {
	if in.Account == "" {
		return model.NewFailDefault("账号不能为空")
	}
	in.Pass = ""
	sorm.DB.UpdateById(in)
	return model.NewOK(nil)
}

// 删除
// @Router [delete] [/sysusers/:id]
func (SysUsersController) Delete(c *gin.Context) any {
	id := c.Param("id")
	if id == "" {
		return model.NewFailDefault("主键不能为空")
	}
	sorm.DB.Delete(entity.SysUsers{Account: id})
	return model.NewOK(nil)
}

type SysUsersQuery struct {
	Page      model.PageInfo  `json:"page"`
	QueryData entity.SysUsers `json:"queryData"`
}

// 查询列表
// @Router [post] [/sysusers/page]
func (SysUsersController) QueryTables(c *gin.Context, in *SysUsersQuery) any {
	sql := `select * from sys_users a where 1=1 `
	data := make([]entity.SysUsers, 0)
	b := sbuilder.StructToBuilder(in.QueryData, sql)
	sql, values := b.Build()
	return sorm.DB.SelectPage(&data, in.Page, sql, values...)
}

// 分页下拉
// @Router [post] [/sysusers/list]
func (SysUsersController) QuerySelect(c *gin.Context, in *model.SelectQueryDTO) any {
	sql := `select a.account as value, name as label from sys_users a where account is not null`
	data := make([]model.SelectVO, 0)
	b := sbuilder.Builder(sql)
	b.Like("CONCAT(account,name)", in.Label)
	b.Multiple().Ors(b.In("account", in.Selected))
	sql, values := b.Build()
	return sorm.DB.SelectPage(&data, in.Page, sql, values...)
}
